package com.hngy.xpq.shoppingcartmodule.ui.home;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProviders;
import androidx.recyclerview.widget.RecyclerView;
import androidx.recyclerview.widget.StaggeredGridLayoutManager;

import com.hngy.xpq.shoppingcartmodule.R;
import com.hngy.xpq.shoppingcartmodule.adapter.ListAdapter;
import com.hngy.xpq.shoppingcartmodule.assets.XpqIcoMoon;
import com.hngy.xpq.shoppingcartmodule.assets.XpqIcoMoonUtils;
import com.hngy.xpq.shoppingcartmodule.bean.Cart;
import com.hngy.xpq.shoppingcartmodule.bean.Shop;
import com.hngy.xpq.shoppingcartmodule.database.SqlCart;
import com.hngy.xpq.shoppingcartmodule.database.SqlShop;
import com.hngy.xpq.shoppingcartmodule.tool.alg;

import java.util.List;

public class HomeFragment extends Fragment {

    private HomeViewModel homeViewModel;
    private RecyclerView listShop;          // 数据渲染控件
    private List<Shop> shopList;            // 数据地址
    private List<Cart> cartList;            // 数据地址
    private SqlShop sqlShop;                // sqLite数据库
    private SqlCart sqlCart;                // sqLite数据库 SqlCart
    private Button homeCart;
    private TextView homeCartNumber;

    public View onCreateView(@NonNull LayoutInflater inflater,
                             ViewGroup container, Bundle savedInstanceState) {
        homeViewModel =
                ViewModelProviders.of(this).get(HomeViewModel.class);
        View root = inflater.inflate(R.layout.fragment_home, container, false);
        init(root);           // 初始化
        return root;
    }

    private void init(View root) {
        // SQL
        sqlShop = new SqlShop(root.getContext());
        sqlCart = new SqlCart(root.getContext());
        // Model
        shopList = homeViewModel.getListShop(sqlShop);
        cartList = homeViewModel.getCartList(sqlCart, root);
        // View
        listShop = root.findViewById(R.id.listShop);
        homeCart = root.findViewById(R.id.homeCart);
        homeCartNumber = root.findViewById(R.id.homeCartNumber);
        // UI渲染
        homeCart.setText(XpqIcoMoon.CART);
        XpqIcoMoonUtils.setIOC(homeCart);
        homeCartNumber.setText(String.valueOf(alg.CountZPrice(cartList).get("number")));
        // 数据渲染
        getListAdapter();
    }

    // List适配器
    private void getListAdapter() {
        StaggeredGridLayoutManager layoutManager = new StaggeredGridLayoutManager(1,StaggeredGridLayoutManager.VERTICAL);
        listShop.setLayoutManager(layoutManager);
        ListAdapter adapter = new ListAdapter(shopList, homeCartNumber);
        listShop.setAdapter(adapter);
    }
}